<!--管理员主页--管理员一栏内容-->
<template>
    <div class="admin-manager-container">
        <div class="header-actions">
            <h2>管理员管理</h2>
            <el-button type="primary" @click="openAddAdminDialog">新增管理员</el-button>
        </div>

        <!-- 管理员列表表格 -->
        <el-table :data="adminList" v-loading="loading">
            <el-table-column prop="id" label="ID" show-overflow-tooltip />
            <el-table-column label="头像">
                <template #default="scope">
                    <el-avatar :size="40" :src="scope.row.avatar">
                        <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" />
                    </el-avatar>
                </template>
            </el-table-column>
            <el-table-column prop="username" label="用户名" show-overflow-tooltip />
            <el-table-column prop="age" label="年龄" width="70">
                <template #default="scope">
                    {{ scope.row.age || '未知' }}
                </template>
            </el-table-column>
            <el-table-column prop="gender" label="性别">
                <template #default="scope">
                    {{ scope.row.gender === 1 ? '男' : scope.row.gender === 2 ? '女' : '未知' }}
                </template>
            </el-table-column>
            <el-table-column prop="phone" label="电话">
                <template #default="scope">
                    {{ scope.row.phone || '未知' }}
                </template>
            </el-table-column>
            <el-table-column prop="email" label="邮箱" show-overflow-tooltip>
                <template #default="scope">
                    {{ scope.row.email || '未知' }}
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip>
                <template #default="scope">
                    {{ formatDate(scope.row.createTime) }}
                </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="更新时间" show-overflow-tooltip>
                <template #default="scope">
                    {{ formatDate(scope.row.updateTime) }}
                </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" align="center">
                <template #default="scope">
                    <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                        {{ scope.row.status === 1 ? '正常' : '禁用' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="180" align="center" fixed="right">
                <template #default="scope">
                    <div v-if="isSuperAdmin">
                        <el-button :type="scope.row.status === 1 ? 'danger' : 'success'" size="small"
                            @click="toggleAdminStatus(scope.row)">
                            {{ scope.row.status === 1 ? '禁用' : '启用' }}
                        </el-button>
                        <el-button type="danger" size="small" @click="deleteAdmin(scope.row)">
                            删除
                        </el-button>
                    </div>
                    <div v-else>
                        <p>暂无操作</p>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <div class="pagination-container">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper" :total="total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>

        <!-- 新增管理员对话框 -->
        <el-dialog v-model="addAdminDialogVisible" title="新增管理员" width="30%" :close-on-click-modal="false">
            <el-form ref="adminFormRef" :model="adminForm" :rules="adminRules" label-width="100px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="adminForm.username" placeholder="请输入用户名"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="adminForm.password" type="password" placeholder="请输入密码" show-password></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                    <el-input v-model="adminForm.confirmPassword" type="password" placeholder="请再次输入密码"
                        show-password></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="addAdminDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleAddAdmin" :loading="submitLoading">确认</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import apiClient from '@/api/api'

// 管理员列表数据
interface Admin {
    id: number
    username: string
    avatar: string
    age: number
    gender: number
    phone: string
    email: string
    createTime: string
    updateTime: string
    status: number
}

// 管理员列表数据，用于存储从后端获取的管理员信息
const adminList = ref<Admin[]>([])
// 加载状态标志，用于控制表格的加载动画
const loading = ref(false)
// 数据总条数，用于分页显示
const total = ref(0)
// 当前页码，默认为第1页
const currentPage = ref(1)
// 每页显示的数据条数，默认为10条
const pageSize = ref(10)

// 新增管理员表单
const addAdminDialogVisible = ref(false)
const adminForm = ref({
    username: '',
    password: '',
    confirmPassword: ''
})
const adminFormRef = ref()
const submitLoading = ref(false)
// 是否是超级管理员
const isSuperAdmin = ref(false)
// 表单验证规则
const adminRules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度应在3到20个字符之间', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度至少为6位', trigger: 'blur' }
    ],
    confirmPassword: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        {
            validator: (rule: any, value: string, callback: (error?: Error) => void) => {
                if (value !== adminForm.value.password) {
                    callback(new Error('两次输入的密码不一致'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ]
}

// 获取管理员列表
const getAdminList = async () => {
    loading.value = true
    try {
        const response = await apiClient.get('/user/getAdminList', {
            params: {
                page: currentPage.value,
                size: pageSize.value
            }
        })
        adminList.value = response.data.data.list
        total.value = response.data.data.total
    } catch (error) {
        console.error('获取管理员列表失败:', error)
        ElMessage.error('获取管理员列表失败')
    } finally {
        loading.value = false
    }
}

// 格式化日期
const formatDate = (dateString: string) => {
    if (!dateString) return ''
    const date = new Date(dateString)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 切换管理员状态（启用/禁用）
const toggleAdminStatus = async (admin: Admin) => {
    const action = admin.status === 1 ? '禁用' : '启用'
    try {
        await ElMessageBox.confirm(
            `确定要${action}管理员 ${admin.username} 吗？`,
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        const response = await apiClient.put('/user/toggleAdminStatus', {
            id: admin.id,
            status: admin.status === 1 ? 0 : 1
        })

        if (response.data.code === 1) {
            ElMessage.success(`${action}成功`)
            getAdminList() // 刷新列表
        } else {
            ElMessage.error(response.data.message || `${action}失败`)
        }
    } catch (error) {
        console.error(`${action}管理员失败:`, error)
    }
}

// 删除管理员
const deleteAdmin = async (admin: Admin) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除管理员 ${admin.username} 吗？此操作不可恢复！`,
            '警告',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        const response = await apiClient.delete('/user/deleteAdmin', {
            params: {
                id: admin.id
            }
        })

        if (response.data.code === 1) {
            ElMessage.success('删除管理员成功')
            getAdminList() // 刷新列表
        } else {
            ElMessage.error(response.data.message || '删除管理员失败')
        }
    } catch (error) {
        console.error('删除管理员失败:', error)
    }
}

// 打开新增管理员对话框
const openAddAdminDialog = () => {
    adminForm.value = {
        username: '',
        password: '',
        confirmPassword: ''
    }
    addAdminDialogVisible.value = true
}

// 新增管理员
const handleAddAdmin = async () => {
    if (!adminFormRef.value) return

    await adminFormRef.value.validate(async (valid: boolean) => {
        if (!valid) return

        submitLoading.value = true
        try {
            const response = await apiClient.post('/user/addAdmin', {
                username: adminForm.value.username,
                password: adminForm.value.password
            })

            if (response.data.code === 1) {
                ElMessage.success('新增管理员成功')
                addAdminDialogVisible.value = false
                getAdminList() // 刷新列表
            } else {
                ElMessage.error(response.data.message || '新增管理员失败')
            }
        } catch (error) {
            console.error('新增管理员失败:', error)
            ElMessage.error('新增管理员失败')
        } finally {
            submitLoading.value = false
        }
    })
}

// 分页处理
const handleSizeChange = (val: number) => {
    pageSize.value = val
    getAdminList()
}
// 分页处理
const handleCurrentChange = (val: number) => {
    currentPage.value = val
    getAdminList()
}
// 判断是否是超级管理员
const checkIsSuperAdmin = async () => {
    await apiClient.get('/user/isSuperAdmin')
        .then((response) => {
            isSuperAdmin.value = response.data.code === 1
        })
}
// 组件挂载时获取管理员列表
onMounted(async () => {
    document.title = '管理员管理'
    getAdminList()
    checkIsSuperAdmin()
})
</script>

<style scoped>
.admin-manager-container {
    padding: 20px;
    overflow-x: auto;
}

.header-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
}

.el-table {
    width: 100%;
}
</style>